package gw.com.android.ui.me_post;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.gwtsz.gts2.hx.R;

import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.DataManager;
import gw.com.android.presenter.PhoneLoginPresenter;
import gw.com.android.presenter.http.DiscussRequest;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.dialog.ImageOperationPopWindow;
import gw.com.android.ui.onlive.DiscussData;
import gw.com.android.ui.views.ImageWatcher;
import gw.com.android.utils.IOUtils;
import gw.com.android.utils.PackStatis;
import gw.com.jni.library.terminal.GTSConst;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.interfaces.ReqCallBack;
import www.com.library.model.DataItemDetail;
import www.com.library.util.StringUtils;
import www.com.library.view.XRecyclerView;

import static gw.com.android.presenter.http.DiscussRequest.TRADE_TYPE_ALL;

/**
 * 我的帖子
 */
public class MyPostActivity extends BaseActivity {

    private MyPostAdapter adapter;
    private ImageWatcher imageWatcher;
    private DiscussRequest request;
    private String userNo;

    @BindView(R.id.recycler_view)
    XRecyclerView recycler_view;
    @BindView(R.id.tv_to_add)
    TextView tv_to_add;
    @BindView(R.id.ll_no_content)
    LinearLayout ll_no_post;
    @BindView(R.id.ll_has_post)
    LinearLayout ll_has_post;

    @Override
    protected int getLayoutView() {
        return R.layout.activity_my_post;
    }

    @Override
    protected void initLayoutView() {
        mTitleBar.setAppTitle(R.string.button_my_post);

        imageWatcher = (ImageWatcher) findViewById(R.id.v_image_watcher);
        imageWatcher.setOnPictureLongPressListener(new LongPressListener());

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);// 布局管理, 默认纵向的，
        recycler_view.setLayoutManager(linearLayoutManager);//设置RecyclerView 布局
        adapter = new MyPostAdapter(this);
        recycler_view.setAdapter(adapter);
        recycler_view.hideFooter();
        recycler_view.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(userNo);
            }

            @Override
            public void onLoadMore() {
                nextPage();
            }
        });

        request = new DiscussRequest();

        tv_to_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PackStatis.getToService("clickPublish", PackStatis.EventCategory.ME.getValue(), null, null);
                //检查当前是不是真实用户。
                if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_REAL)
                    ActivityManager.showDiscussAdd(MyPostActivity.this);
                else
                    new ToastPopWindow(MyPostActivity.this, getString(R.string.home_discuss_not_real_2)).show();
            }
        });
    }

    private DataItemDetail mAccountInfo;

    @Override
    protected void initViewData() {
        adapter.setWatcher(imageWatcher);

        //如果是模拟用户登录，那么，查询当前模拟用户是否关联了真实用户
        //如果关联了，那么就显示真实用户的 “我的关注”; 否则，就显示所有分析师
        if (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_DEMO) {
            int mSeq = GTSDataListener.curSeq++;
            String loginPass = GTConfig.instance().mUserPwd;
            mAccountInfo = DataManager.instance().mAccount;
            String loginPhoneNo = mAccountInfo.getString(GTSConst.JSON_KEY_PHONE);
            if (!StringUtils.isEmpty(loginPhoneNo)) {
                if (loginPhoneNo.startsWith("86")) {
                    loginPhoneNo = loginPhoneNo.substring(2, loginPhoneNo.length());
                }
            }
            Log.d("checkDemoTagParam", "" + mSeq + " - " + loginPhoneNo + "-" + loginPass);
            PhoneLoginPresenter.instance().PhoneLoginFun(AppContances.NORMALREQ_TYPE_GET_CUSTOMERBYMOBILE, mSeq, loginPhoneNo, loginPass,
                    new PhoneLoginPresenter.OnMobileReqResultListener() {
                        @Override
                        public void reqResultSuccess(Object mObject) {
                            JSONObject obj = (JSONObject) mObject;
                            JSONObject result = obj.optJSONObject("result");
                            if (!result.isNull("customerNumber") && !result.isNull("demoCustomerNumber")) {//就是没有绑定
                                String customerNumber = result.optString("customerNumber");
                                Log.d("checkDemoTag", "当前登录的是模拟账户,已绑定真实帐户:" + customerNumber);
                                //如果已经绑定了真实账户，那就让我的关注显示 真实账户的关注数据
                                userNo = customerNumber;
                                loadData(userNo);
                                fetchLocalData();
                            } else {
                                Log.d("checkDemoTag", "当前登录的是模拟账户并且没有绑定真实账户");
                                //如果没有绑定，那就显示所有分析师
                                refreshUi(null);
                            }
                        }

                        @Override
                        public void reqResultFail(int failCode) {
                            Log.d("checkDemoTag", "请求失败");
                        }
                    });
        } else {
            userNo = GTConfig.instance().mCurName;
            loadData(userNo);//那就显示默认的咯，
            fetchLocalData();
        }


    }

    private void loadData(String userNo) {
        request.getList(new ReqCallBack<List<DiscussData>>() {
            @Override
            public void onReqSuccess(List<DiscussData> result) {
                Log.d("resultSize", "" + (result == null ? "list是空 " : result.size()));
//                result = null;
                recycler_view.refreshComplete();
                refreshUi(result);
            }

            @Override
            public void onReqFailed(String errorMsg) {
                new ToastPopWindow(MyPostActivity.this, "服务器错误:" + errorMsg).show();
                recycler_view.refreshComplete();
                refreshUi(null);
            }
        }, TRADE_TYPE_ALL, true, userNo);//先改成false，看看数据显示的UI TODO 记得改回去
    }

    /**
     * 加载更多
     */
    private void nextPage() {
        if (request == null) {
            request = new DiscussRequest();
        }
        request.nextPage(new ReqCallBack<List<DiscussData>>() {
            @Override
            public void onReqSuccess(List<DiscussData> result) {
                Log.d("nextPage", "" + (result == null ? "list是空 " : result.size()));
                recycler_view.loadMoreComplete();
                recycler_view.setNoMore(!request.hasNextPage());
                adapter.addData(result);
            }

            @Override
            public void onReqFailed(String errorMsg) {
                recycler_view.loadMoreComplete();
                //mListView.setNoMore(false);
                new ToastPopWindow(MyPostActivity.this, "服务器错误").show();
            }
        });
    }

    private List<DiscussData> filterUnpassedData(List<DiscussData> result) {
        List<DiscussData> finalData = new ArrayList<>();
        if (result == null) return finalData;
        for (int i = 0; i < result.size(); i++) {
            if (result.get(i).status == 1) {//过滤掉审核状态不是1的（1表示审核通过，0表示未审核，-1表示不通过）
                finalData.add(result.get(i));
            }
        }
        return finalData;
    }

    private void refreshUi(List<DiscussData> result) {
        //过滤掉status不为1的数据记录
        List<DiscussData> filterNotPassedData = filterUnpassedData(result);

        if (null == filterNotPassedData || filterNotPassedData.size() == 0) {
            ll_no_post.setVisibility(View.VISIBLE);
            ll_has_post.setVisibility(View.GONE);
        } else {
            ll_has_post.setVisibility(View.VISIBLE);
            ll_no_post.setVisibility(View.GONE);
            adapter.setData(filterNotPassedData);
        }

        int itemCount = adapter.getItemCount();
        if (itemCount <= 0 || !request.hasNextPage()) {
            recycler_view.setNoMore(false);
            recycler_view.hideFooter();
        } else {
            recycler_view.setNoMore(!request.hasNextPage());
        }
    }

    @Override
    public void onBackPressed() {
        if (imageWatcher != null && imageWatcher.getVisibility() == View.VISIBLE) {
            imageWatcher.handleBackPressed();
        } else
            super.onBackPressed();
    }

    /**
     * 长按图片 ，保存图片
     */
    private class LongPressListener implements ImageWatcher.OnPictureLongPressListener {
        @Override
        public void onPictureLongPress(ImageView v, final String url, int pos) {
            new ImageOperationPopWindow(MyPostActivity.this, new ImageOperationPopWindow.OnSaveListener() {
                @Override
                public void onSave() {
                    saveImage(url);
                }
            }).show();
        }
    }

    private void saveImage(String url) {
        final BaseActivity activity = this;
        if (activity == null) {
            return;
        }
        activity.showLoading();

        String fileName = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date());
        final File file = new File(GTConfig.instance().getRootDirectory() + "/image/" + fileName + ".jpg");

        Glide.with(activity).load(url).downloadOnly(new SimpleTarget<File>() {
            @Override
            public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
                activity.hideLoading();
                if (resource != null && resource.length() > 0) {
                    boolean copy = IOUtils.copy(resource, file);
                    if (copy) {
                        Uri uri = Uri.fromFile(file);
                        activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
                        new ToastPopWindow(activity, AppMain.getAppString(R.string.home_save_success_title)).show();
                        return;
                    }
                }
                new ToastPopWindow(activity, AppMain.getAppString(R.string.home_save_fail_title)).show();
            }

            @Override
            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                activity.hideLoading();
                new ToastPopWindow(activity, AppMain.getAppString(R.string.home_save_fail_title));
            }
        });
    }

    private void fetchLocalData() {
        if (null == request) {
            request = new DiscussRequest();
        }
        List<DiscussData> cacheList = request.fetchLocal(DiscussRequest.TRADE_TYPE_MY_POST, userNo);
        if (cacheList != null && !cacheList.isEmpty()) {
            refreshUi(cacheList);
        }
    }
}
